/**
 * @description 获取随机颜色
 */
export function randomColor() {
  const color = '#' + Math.random().toString(16).substring(2, 8)
  return color.length !== 7 ? 'pink' : color
}

/**
 * @description 获取字母数字组合
 */
export function genRandomStr(size = 4) {
  const range = [
    '0',
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    'a',
    'b',
    'c',
    'd',
    'e',
    'f',
    'g',
    'h',
    'i',
    'j',
    'k',
    'l',
    'm',
    'n',
    'o',
    'p',
    'q',
    'r',
    's',
    't',
    'u',
    'v',
    'w',
    'x',
    'y',
    'z',
    'A',
    'B',
    'C',
    'D',
    'E',
    'F',
    'G',
    'H',
    'I',
    'J',
    'K',
    'L',
    'M',
    'N',
    'O',
    'P',
    'Q',
    'R',
    'S',
    'T',
    'U',
    'V',
    'W',
    'X',
    'Y',
    'Z'
  ]
  const strList = []
  for (let i = 0; i < size; i++) {
    const randomStr = range[Math.floor(Math.random() * range.length)]
    strList.push(randomStr)
  }
  return strList
}

/**
 * @description 获取字母数组组合并生成图片
 */
export function useCaptcha(width = 100, height = 50) {
  // 生成随机内容
  const canvas = document.createElement('canvas')
  canvas.width = width
  canvas.height = height
  const ctx = canvas.getContext('2d')
  const captcha = genRandomStr()
  if (ctx) {
    for (const i in captcha) {
      const str = captcha[i]
      const transLen = (width * 0.8) / captcha.length // 偏移量
      const sizeRatio = 0.4 + 0.4 * Math.random() // 随机文字大小比例
      const degRatio = (Math.random() - 0.5) * 0.5 // 随机旋转比例
      ctx.fillStyle = '#fff'
      ctx.font = height * sizeRatio + 'px serif' // 设置字体大小
      ctx.rotate(degRatio) // 旋转
      ctx.fillText(str, width * 0.1, height * 0.8, width * 0.8) // 填充文字
      ctx.translate(transLen, 0) // 偏移
      ctx.rotate(-degRatio) // 恢复旋转
    }
  }
  const result = {
    imgSrc: canvas.toDataURL(),
    value: captcha.join('')
  }
  return result
}
/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params: any) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName]
    const part = encodeURIComponent(propName) + '='
    if (value !== null && value !== '' && typeof value !== 'undefined') {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== '' && typeof value[key] !== 'undefined') {
            const params = propName + '[' + key + ']'
            const subPart = encodeURIComponent(params) + '='
            result += subPart + encodeURIComponent(value[key]) + '&'
          }
        }
      } else {
        result += part + encodeURIComponent(value) + '&'
      }
    }
  }
  return result
}
